﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Configuration;

namespace DataProcess
{
	public partial class frmPiWordsTotal : Form
	{
		public frmPiWordsTotal()
		{
			InitializeComponent();
			dtpStart.Value = dtpEnd.Value.AddMonths(-1);
			dataGridView1.AutoGenerateColumns = false;
		}
		private Regex HtmlTag = new Regex("<[^>]+>", RegexOptions.Compiled);

		private void btnTotal_Click(object sender, EventArgs e)
		{
			string start = dtpStart.Value.ToString("yyyy-MM-dd"), end = dtpEnd.Value.ToString("yyyy-MM-dd");
			DataTable dt = new DataTable();
			var config = ConfigurationManager.ConnectionStrings["CDESpecification"];
			if (config == null)
			{
				MessageBox.Show("没有找到数据库配置信息（节点：CDESpecification）");
				return;
			}
			SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(config.ConnectionString);
			builder.Password = builder.UserID;
			using (SqlConnection conn = new SqlConnection(builder.ConnectionString))
			{
				conn.Open();
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = string.Format("select b.username,a.gzuserid,count(a.dcid) as articles from cde_document a left join st_user b on a.gzuserid=b.userid where (gzdate between '{0}' and '{1}') and a.dtid=2 group by a.gzuserid,b.username", start, end);
					using (var reader = cmd.ExecuteReader())
					{
						dt.Load(reader);
					}
					dt.Columns.Add("words", typeof(long));
					for (int i = 0; i < dt.Rows.Count; i++)
					{
						cmd.CommandText = string.Format("select a.content from [cde_docparagraph] a inner join cde_document b on a.dcid=b.dcid where a.[abolished]=0 and b.gzuserid={2} and (b.gzdate between '{0}' and '{1}') and b.dtid=2 and a.content  is not null", start, end, dt.Rows[i]["gzuserid"]);
						long total = 0;
						using (var reader = cmd.ExecuteReader())
						{
							while (reader.Read())
							{
								total += System.Web.HttpUtility.HtmlDecode(Regex.Replace(HtmlTag.Replace(reader["content"].ToString(), string.Empty), "\\s", string.Empty).Replace("\r\n", string.Empty)).Length;
							}
						}
						dt.Rows[i]["words"] = total;
					}
				}
			}

			dataGridView1.DataSource = dt;
		}
	}
}
